<?php

namespace Kunfeng\Dify\Model\Datasets;

/**
 * 处理规则配置
 */
class ProcessRuleRules
{
    private $preProcessingRules;
    private $segmentation;
    private $parentMode;
    private $subchunkSegmentation;

    public function __construct(array $data = [])
    {
        $this->preProcessingRules = array_map(function($item) {
            return PreProcessingRule::fromArray($item);
        }, $data['pre_processing_rules'] ?? []);
        $this->segmentation = isset($data['segmentation']) ? Segmentation::fromArray($data['segmentation']) : null;
        $this->parentMode = $data['parent_mode'] ?? 'full-doc';
        $this->subchunkSegmentation = isset($data['subchunk_segmentation']) ? SubchunkSegmentation::fromArray($data['subchunk_segmentation']) : null;
    }

    /**
     * 从数组创建
     */
    public static function fromArray(array $data): self
    {
        return new self($data);
    }

    // Getters
    public function getPreProcessingRules(): array
    {
        return $this->preProcessingRules;
    }

    public function getSegmentation(): ?Segmentation
    {
        return $this->segmentation;
    }

    public function getParentMode(): string
    {
        return $this->parentMode;
    }

    public function getSubchunkSegmentation(): ?SubchunkSegmentation
    {
        return $this->subchunkSegmentation;
    }

    /**
     * 转换为数组
     */
    public function toArray(): array
    {
        $data = [
            'pre_processing_rules' => array_map(function($rule) {
                return $rule->toArray();
            }, $this->preProcessingRules),
            'parent_mode' => $this->parentMode,
        ];

        if ($this->segmentation !== null) {
            $data['segmentation'] = $this->segmentation->toArray();
        }
        if ($this->subchunkSegmentation !== null) {
            $data['subchunk_segmentation'] = $this->subchunkSegmentation->toArray();
        }

        return $data;
    }
}
